/**
 * Example
  <sd-swipper bindcelltaped="onCellTaped" 
    bindwillediting='onCellWillEditing' 
    ext-data="{{({key: 'value'})}}">
    <view slot="cell-content" class='cell-content'>
      测试
    </view>
    <view slot="cell-delete" class='cell-delete'>
      删除
    </view>
  </sd-swipper>

 */
// 侧滑删除组件
Component({
  
  isInEditing: false,

  options: {
    multipleSlots: true 
  },

  properties: {
    extData: {
      type: [Object, Number, String]
    }
  },

  data: {

  },

  methods: {

    onCellTouchStart: function (e) {
      let isInEditing = this.isInEditing;

      if (isInEditing) {
        this.endEditing();
      } else {
        this.touchStartX = e.changedTouches[0].clientX;
        this.touchStartY = e.changedTouches[0].clientY;
        this.triggerEvent('willediting', { extData: this.data.extData });
      }
    },

    onCellTouchEnd: function (e) {
      let isInEditing = this.isInEditing;
      if (isInEditing) {
        return;
      }
      let x = e.changedTouches[0].clientX;
      let y = e.changedTouches[0].clientY;
      let touchStartX = this.touchStartX;
      let touchStartY = this.touchStartY;

      if (touchStartX - x > 3 && Math.abs(touchStartY - y) < 20) {
        this.showEditing();
      } else if (touchStartX - x < -3 && Math.abs(touchStartY - y) < 20) {
        this.endEditing();
      }
    },

    onCellTap: function (e) {      // cell点击处理
      if (this.isInEditing) { return; }
      this.triggerEvent('celltaped', { extData: this.data.extData});
    },

    rpxToPx: function (rpx) {
      return parseInt(rpx / 750 * this.windowWidth);
    },

    endEditing: function () {      // 结束编辑状态
      if (!this.isInEditing) {
        return;
      }
      let deleteAnimator = this.deleteAnimator;
      let animation = deleteAnimator.translateX(0).step();
      this.setData({
        'deleteAnimation': animation.export(),
      });

      setTimeout(() => {
        this.setData({
          'deleteAnimation': '',
        }, () => {
          this.isInEditing = false;
        });
      }, 350);
    },

    showEditing: function () {     // 开启编辑状态
      let deleteAnimator = this.deleteAnimator;
      let animation = deleteAnimator.translateX(this.rpxToPx(-150)).step();
      this.setData({
        'deleteAnimation': animation.export(),
      });
      this.isInEditing = true;
    }
  },

  attached: function () {
    this.windowWidth = wx.getSystemInfoSync().windowWidth;
    // 删除动画器
    this.deleteAnimator = wx.createAnimation({
      duration: 350,
      timingFunction: 'ease-out'
    });
    // 是否处于编辑状态
    this.touchStartX = 0;
    this.touchStartY = 0;
  }
})
